package com.SpringBoot.brand.service;


import com.SpringBoot.Util.Pager;
import com.SpringBoot.Util.Result;
import com.SpringBoot.brand.mapper.BrandMapper;
import com.SpringBoot.brand.pojo.Brand;
import com.SpringBoot.file.FileService;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;

/**
 * <p>
 * 品牌表 服务实现类
 * </p>
 *
 * @author bxk
 * @since 2025-09-15
 */
@Service
public class BrandService {
    private final FileService fileService;
    private final BrandMapper brandMapper;

    public BrandService(FileService fileService, BrandMapper brandMapper) {
        this.fileService = fileService;
        this.brandMapper = brandMapper;
    }

    public Result addBrand(Brand brand) {
        Brand existBrand = brandMapper.selectByName(brand.getName());
        if (existBrand != null) {
            if(existBrand.getStatus() == 1){
                brand.setStatus(0);
                brandMapper.updateBrand(brand);
                return Result.success("添加成功");
            }
            else {
                return Result.error(409,"品牌已存在");
            }
        }
        else {
            brandMapper.insert(brand);
            return Result.success("添加成功");
        }
    }

    public Result updateBrand(Brand brand) {
        System.out.println(brand);
        Brand existBrand = brandMapper.selectById(brand.getBrandId());
        if(existBrand == null){
            return Result.error(404,"该品牌不存在");
        }
        if(existBrand.getStatus() != 0 ){
            return Result.error(404,"该品牌已被删除");
        }
        brandMapper.updateBrand(brand);
        return Result.success("修改成功");
    }

    public Result deleteById(Integer brandId,Integer status) {
        brandMapper.deleteById(brandId,status);
        return Result.success("操作成功");
    }

    public Result selectByNameLike(String name){
        List<Brand> brands = brandMapper.selectByNameLike(name);
        if(brands.size() <= 0){
            return Result.error(404,"没有该品牌");
        }else {
            return Result.success(brands);
        }
    }

    public Result selectBrandName(){
        List<String> brandNames = brandMapper.selectBrandName();
        return Result.success(brandNames);
    }

    public Result selectAllBrand(Integer pageNum, Integer pageSize){
        //查询总记录数
        Integer recordCount = brandMapper.count();
        //构建分页信息对象
        Pager pager = new Pager(pageNum, pageSize, recordCount);
        //根据pager查询需要的数据
        List<Brand> list = brandMapper.selectAll(pager.getStart(), pageSize);
        //将分页信息和查询到的数据一起返回到前端
        HashMap<String,Object> map = new HashMap<>();
        map.put("pager",pager);
        map.put("list",list);
        return Result.success(map);
    }

}
